<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\UserLoginModel;
use App\Model\UsersModel;
use App\Model\WithdrawalModel;
use App\Services\WechatServices;
use Illuminate\Support\Facades\DB;
use PHPUnit\Exception;

class UsersDao extends BaseDao
{
    public static function builder_user_query($params = [])
    {
        $query = UsersModel::query();
        $query->when(checkIsHasField($params,'user_login_id'),function ($query)use ($params){
            $query->where('user_login_id',$params['user_login_id']);
        });
        $query->when(checkIsHasField($params,'vip_level'),function ($query)use ($params){
            $query->where('vip_level',$params['vip_level']);
        });
        $query->when(checkIsHasField($params,'vip_index_level'),function ($query)use ($params){
            $query->where('vip_index_level',$params['vip_index_level']);
        });



        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'spread_id'),function ($query)use ($params){
            $query->where('spread_id',$params['spread_id']);
        });


        //查询手机号
        $query->when(checkIsHasField($params,'phone_like'),function ($query)use ($params){
            $usersLoginIds = self::builder_user_login_query()->where('user_login_phone','LIKE','%'.$params['phone_like'].'%');
            if(!$usersLoginIds->exists()){
                $query->whereIn('user_login_id',[99999999]);
            }else{
                $query->whereIn('user_login_id',$usersLoginIds->pluck('user_login_id')->toArray());
            }
        });



        return $query->with('user_login_info');
    }


    public static function builder_user_login_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = UserLoginModel::query();
        $query->when(checkIsHasField($params,'user_login_id'),function ($query)use ($params){
            $query->where('user_login_id',$params['user_login_id']);
        });
        $query->when(checkIsHasField($params,'user_login_phone'),function ($query)use ($params){
            $query->where('user_login_phone',$params['user_login_phone']);
        });

        return $query;
    }

    /**
     * @param array $params
     * @return array
     * @throws SysExceptions
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function register(array $params): array
    {
        checkForData(['code','code2'],['请输入手机号','请输入手机号'],$params);
        $resultData = WechatServices::wechat_login($params['code'],'','',$params['code2']);
        //获取用户手机号的基础
        $query = self::builder_user_login_query([
            'user_login_phone'=>$resultData['phone']
        ]);
        //创建账号
        if(!$query->exists()){
            $query->create(['user_login_phone'=>$resultData['phone']]);
        }

        if($query->update([
            'openid'=>$resultData['openid']
        ]) === false){
            self::error('失败');
        }
        return $query->first()->toArray();
    }

    public static function u_l_users(array $params)
    {
        checkForData(['user_login_id'],['请登录用户'],$params);
        return self::builder_user_query([
            'user_login_id'=>$params['user_login_id']
        ])->get()->toArray();
    }

    /**
     * @param array $params
     * @return void
     * @throws SysExceptions
     */
    public static function login_u(array $params)
    {
        checkForData(['user_login_id'],['请登录用户'],$params);
        $inserData = [
            'user_login_id'=>$params['user_login_id'],
            'nickname'=>'tree_'.time(),
            'pay_pass'=>password_hash('123456',PASSWORD_DEFAULT)
        ];
        DB::beginTransaction();

        try {
            if(checkIsHasField($params,'spread_id')){
                $inserData['spread_id'] = $params['spread_id'];

            }
            $result = self::builder_user_query(['user_login_id'=>$params['user_login_id']])->create($inserData);
            DB::update("UPDATE tree_users SET usersids = ',' WHERE usersids IS NULL;");
            if(checkIsHasField($params,'spread_id')){
                $spread_id = $params['spread_id'];
                while(true){
                    if($spread_id == 0){
                        break;
                    }
                    $userInfo = self::builder_user_query([
                        'user_id'=>$spread_id
                    ])->first()->toArray();
                    UsersDao::builder_user_query([
                        'user_id'=>$spread_id
                    ])->update([
                        'usersids'=>$userInfo['usersids'].$result->user_id.','
                    ]);
                    $spread_id = UsersDao::builder_user_query([
                        'user_id'=>$spread_id
                    ])->value('spread_id');
                }
            }


            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
        return  $result;
    }

    public static function user_info(array $params)
    {
        $info =  self::builder_user_query(['user_id'=>$params['user_id']])->first()->toArray();
        $info['address'] = AddressDao::builder_query([
            'user_id'=>$params['user_id']
        ])->orderByDesc('is_default')->first();
        $info['user_login_info'] = self::builder_user_login_query([
            'user_login_id'=>$info['user_login_id']
        ])->first()->toArray();
        return $info;
    }

    public static function set_id_card(array $params)
    {
        checkForData(['id_card','real_name'],['请输入身份证号','请输入真实姓名'],$params);
        if(self::builder_user_query(['user_id'=>$params['user_id']])->update([
            'id_card'=>$params['id_card'],
            'real_name'=>$params['real_name'],
        ]) === false){
            self::error('设置失败');
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function update_pay_pass(array $params)
    {
        checkForData(['old_pay_pass','pay_pass'],['请输入旧密码','请输入新密码'],$params);
        $info = self::builder_user_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if(!password_verify($params['old_pay_pass'],$info['pay_pass']))
            self::error('原密码不正确');
        if(self::builder_user_query(['user_id'=>$params['user_id']])->update([
                'pay_pass'=>password_hash($params['pay_pass'],PASSWORD_DEFAULT),
            ]) === false){
            self::error('设置失败');
        }
    }

    public static function widthwal(array $params)
    {
        checkForData(['nums'],['请输入数量'],$params);
        $userInfo = self::builder_user_query(['user_id'=>$params['user_id']])->first()->toArray();
        if($userInfo['card_json_data'] == NULL){
            self::error('请绑定银行卡');
        }
        if($userInfo['balance'] < $params['nums']){
            self::error('余额不足');
        }
        DB::beginTransaction();
        $dataFee = $params['nums']*0.06;
        try {
            BillsDao::moneyUpdate($params['user_id'],-($params['nums']),'用户提现');

            //扣除手续费并且回流


            WithdrawalModel::query()->create([
                'card_json_data'=>$userInfo['card_json_data'],
                'user_id'=>$params['user_id'],
                'fee'=>$dataFee,
                'nums'=>$params['nums']-$dataFee,
                'status'=>0
            ]);
            //金额

            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function setCardJson(array $params)
    {
        checkForData(['name','card_no','card_kai'],['请输入姓名','请输入卡号','请输入开户行'],$params);
        if(self::builder_user_query(['user_id'=>self::deleteParamId($params,'user_id')])->update(['card_json_data'=>json_encode($params,JSON_UNESCAPED_UNICODE)]) === false){
            self::error('设置失败');
        }
    }

    public static function widthwal_lists(array $params)
    {
        $list =  WithdrawalModel::query()->where([
            'user_id'=>$params['user_id']
        ]);

        if(checkIsHasField($params,'status')){
            $list->where('status',$params['status']);
        }



        return $list->paginate();
    }

    public static function bills(array $params): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return BillsDao::bills_query($params)->orderByDesc('created_at')->paginate();
    }

    public static function bills_score(array $params): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return BillsScoreDao::bills_query($params)->orderByDesc('created_at')->paginate();
    }

    /**
     * @throws SysExceptions
     */
    public static function score_to_balance(array $params)
    {
        checkForData(
            ['nums'],
            ['请输入兑换数量'],
            $params
        );
        if(!($params['nums'] > 0)){
            self::error('请输入大于0的数字');
        }
        $user_info = self::builder_user_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($user_info['score'] < $params['nums']){
            self::error('用户积分不足');
        }
        //积分按照价格兑换成现金
        $dataFee = bcmul($params['nums'],0.1,2);
        $params['nums'] = bcsub($params['nums'],$dataFee,10);
        $dataPrice = bcmul($params['nums'],CommonDao::real_time_price(),2);

        DB::beginTransaction();
        try {
            //扣除积分并且收取10%手续费
            BillsDao::moneyUpdate($params['user_id'],$dataPrice,'积分兑换现金');
            BillsScoreDao::moneyUpdate($params['user_id'],-($params['nums']),'积分兑换现金扣除');
            sleep(1);
            BillsScoreDao::moneyUpdate($params['user_id'],-($dataFee),'积分兑换扣除手续费');
            //兑换时候单价
            UsersDao::builder_user_query([
                'user_id'=>$params['user_id']
            ])->increment('w_prices',$params['nums']);
            CommonDao::mixGoodsPrice($dataPrice);
            //10%回流
            $scorex = $dataFee;
            CommonDao::mixScorePrice($scorex);
            //积分发放到用户里面
            BillsScoreDao::moneyUpdate(CommonDao::$user_sys_id,$scorex,'手续费二次回流(沉淀)');
            DB::commit();
        }catch ( \Exception $exception){
            DB::rollBack();
            var_dump($exception->getMessage());

            self::error($exception->getMessage());
        }

    }

    public static function score_to_balance_to_user(array $params)
    {
        checkForData(
            ['nums','real_user_id'],
            ['请输入兑换数量','请输入转账用户ID'],
            $params
        );
        $user_info = self::builder_user_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($user_info['score'] < $params['nums']){
            self::error('用户积分不足');
        }
        $dataFee = bcmul($params['nums'],0.1,2);
        $params['nums'] = bcsub($params['nums'],$dataFee,10);
        $dataPrice = bcmul($params['nums'],CommonDao::real_time_price(),2);

        DB::beginTransaction();
        try {
            //扣除积分并且收取10%手续费
            BillsDao::moneyUpdate($params['real_user_id'],$dataPrice,'收到积分转账(用户:'.$params['user_id'].')');
            BillsScoreDao::moneyUpdate($params['user_id'],-($dataFee),'积分兑换扣除手续费');
            BillsScoreDao::moneyUpdate($params['user_id'],-($params['nums']),'积分转账扣除(用户:'.$params['real_user_id'].')');
            CommonDao::mixGoodsPrice($dataPrice);
            //10%回流
            $scorex = bcdiv($dataFee,CommonDao::real_time_price(),10);
            CommonDao::mixScorePrice($scorex);
            //积分发放到用户里面
            BillsScoreDao::moneyUpdate(CommonDao::$user_sys_id,$scorex,'手续费二次回流(沉淀)');
            DB::commit();
        }catch ( \Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function balance_to_user(array $params)
    {
        checkForData(
            ['nums','real_user_id'],
            ['请输入兑换数量','请输入转账用户ID'],
            $params
        );
        $user_info = self::builder_user_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        if($user_info['balance'] < $params['nums']){
            self::error('用户现金不足');
        }
        DB::beginTransaction();
        try {
            BillsDao::moneyUpdate($params['user_id'],-($params['nums']),'余额转账扣除');
            BillsDao::moneyUpdate($params['real_user_id'],$params['nums'],'余额转账获得(用户:'.$params['user_id'].')');
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    /**
     * @throws SysExceptions
     */
    public static function forget_pay_pass(array $params)
    {
        checkForData(
            ['phone','code','pay_pass'],
            ['请输入手机号','请输入验证码','请输入支付密码'],
            $params
        );

        if(self::builder_user_query([
            'user_id'=>$params['user_id']
        ])->update([
            'pay_pass'=>password_hash($params['pay_pass'],PASSWORD_DEFAULT)
        ]) === false){
            self::error('修改失败');
        }
    }

    public static function users_count_data(array $params)
    {
        //平级奖励
        $pingji = BillsScoreDao::bills_query([
            'user_id'=>$params['user_id']
        ])->where('title','like','%感恩奖励%')->sum('nums');
        $pingjiKou = BillsScoreDao::bills_query([
            'user_id'=>$params['user_id']
        ])->where('title','like','%贡献奖奖励%')->sum('nums');

        $score = bcadd($pingji,$pingjiKou,10);
        $jingtai = BillsScoreDao::bills_query([
            'user_id'=>$params['user_id']
        ])->where('title','like','%消费获取绿色消费积分%')->sum('nums');
        $dongtai = bcadd(BillsScoreDao::bills_query([
            'user_id'=>$params['user_id']
        ])->where('title','like','%动态%')->sum('nums'),$score,10);
        return [
            'all_count'=>bcadd($jingtai,$dongtai,2),
            'jingtai'=>$jingtai,
            'dongtai'=>$dongtai
        ];
    }

    public static function pageinate(array $params)
    {
        $lists = self::builder_user_query($params)->orderByDesc('created_at')->paginate();
        foreach ($lists as &$value){
            $max_yeji = OrdersDao::getMaxPrices($value['user_id']);
            $all_price = $value['all_prices'];
            //小区业绩
            $value['item_v'] = bcsub($all_price,$max_yeji,2);
            $value['max_yeji'] = $max_yeji == NUll ? 0 : $max_yeji;
        }


        return $lists;
    }

    public static function recharge(array $params)
    {
        checkForData(
            ['money'],
            ['请输入金额'],
            $params
        );
        DB::beginTransaction();
        try {
            BillsDao::moneyUpdate($params['user_id'],$params['money'],'后台充值');
            DB::commit();
        }catch ( Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }

    public static function edit(array $params)
    {
        if(self::builder_user_query([
            'user_id'=>$params['user_id']
        ])->update(['vip_level'=>$params['vip_level'],'message'=>$params['message']]) === false){
            self::error();
        }
    }

    public static function get_tuan_users(array $params): array
    {
        $userInfo = self::builder_user_query([
            'user_id'=>$params['user_id']
        ])->first()->toArray();
        $userInfo['usersids_count'] = count(explode(',',$userInfo['usersids']))-2;
        $all_users = UsersDao::builder_user_query([
            'spread_id'=>$userInfo['user_id']
        ])->get();
        foreach ($all_users as $value){
            $value['spread_prices'] = 0;
            //查询自己的业绩
            $prices = OrdersDao::builder_query([
                'status'=>1
            ])->where('user_id',$value['user_id'])->sum('price');
            if($prices > 0){
                $value['spread_prices'] = $prices;
            }
            $value['usersids_count'] = count(explode(',',$value['usersids']))-2;
        }
        return [
            'user_card_info'=>$userInfo,
            'spear_users'=>$all_users
        ];
    }

    public static function update_user_info(array $params)
    {
        checkForData(
            ['headimgurl','nickname'],
            ['请上传头像','请修改昵称'],
            $params
        );
        if(self::builder_user_query([
            'user_id'=>$params['user_id']
        ])->update([
            'nickname'=>$params['nickname'],
            'headimgurl'=>$params['headimgurl'],
        ]) === false){
            self::error('修改失败');
        }
    }

    public static function recharge_score(array $params)
    {
        checkForData(
            ['nums'],
            ['请输入积分数量'],
            $params
        );
        DB::beginTransaction();
        try {
            //增加积分池
            CommonDao::mixScorePrice($params['nums']);
            BillsScoreDao::moneyUpdate($params['user_id'],$params['nums'],'后台充值');
            DB::commit();
        }catch ( Exception $exception){
            DB::rollBack();
            self::error($exception->getMessage());
        }
    }


}
